package co.fitstart.admin.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.demo2do.core.persistence.annotation.Dynamic;

import co.fitstart.entity.product.Product;
import co.fitstart.entity.product.stat.UserProductBehavior;

/**
 * 
 * @author mohanlan
 *
 */
@Repository("productDaoSupport")
public class ProductDaoSupport {
    
    @Dynamic
    private ProductDao productDao;
    
    /**
     * 
     * @param product
     * @param tags
     */
    public void deleteProductTags(Product product, List<String> tags) {
        
        // check tag deletion
        if(!product.getTags().isEmpty()) {
            
            List<Long> tagsToDelete = new ArrayList<Long>();
            
            // if empty tags, remove all product tags
            if(CollectionUtils.isEmpty(tags)) {
                for(String tag : product.getTags().keySet()) {
                    tagsToDelete.add(product.getTags().get(tag).getId());
                }
            }else { // if not empty tags, remove product tags which not in tags
                for(String tag : product.getTags().keySet()) {
                    if(CollectionUtils.isNotEmpty(tags) && !tags.contains(tag)) {
                        tagsToDelete.add(product.getTags().get(tag).getId());
                    }
                }
            }
            
            // if exit product tag to delete
            if(CollectionUtils.isNotEmpty(tagsToDelete)) {
                productDao.deleteProductTags(product, tagsToDelete);
                }
        }
    }
    
    /**
     * Load user product behavior
     * 
     * @param product
     * @param openid
     * @return
     */
    public UserProductBehavior loadUserProductBehavior(Product product, String openid) {
        
        if(StringUtils.isNotBlank(openid)) {
            return productDao.loadUserProductBehavior(product, openid);
        }
        
        return null;
    }
}
